<template>
    <view>
        <up-popup :show="show" round position="bottom"  @close="onClose" :overlay="true">
            <view class="loginContainer">
                <view class="header">
                    <text class="title">{{ title }}</text>
                    <text class="desc">{{ desc }}</text>
                </view>

                <view class="content">
                    <view class="button-row">
                        <up-button round plain color="#888" class="login-btn" @tap.native="onClose">取消</up-button>
                        <up-button type="primary" color="#396136" round :loading="loading" loading-text="登录中..." class="login-btn" @tap.native="onWxLogin">
                            <up-icon name="weixin-circle-fill" size="20px" style="margin-right: 8px" color="#07C160"/>
                            微信登录
                        </up-button>
                    </view>
                </view>
                <view class="tips">点击登录即代表同意 <text class="agreement_text" @tap="onAgreementTap(1)">《用户协议》</text> 和 <text class="agreement_text" @tap="onAgreementTap(2)">《隐私政策》</text></view>
            </view>
        </up-popup>
    </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { loginFun } from '@/api/port';

// 类型定义
interface Props {
  show?: boolean;
  title?: string;
  desc?: string;
}

interface UserInfo {
  nickName: string;
  avatarUrl: string;
  gender: number;
  city: string;
  province: string;
  country: string;
}

interface LoginResult {
  userInfo: UserInfo;
  token: string;
  userId: string;
}

interface WxLoginResponse {
  code: string;
}

interface UserProfileResponse {
  userInfo: UserInfo;
}

// Props定义
const props = withDefaults(defineProps<Props>(), {
  show: false,
  title: '用户登录',
  desc: '登录后可享受更多服务'
});

// 事件定义
const emit = defineEmits<{
  close: [];
  success: [{ detail: { userInfo: UserInfo; token: string } }];
}>();

// 响应式数据
const loading = ref<boolean>(false);

/**
 * 关闭弹窗
 */
const onClose = (): void => {
  loading.value = false;
  emit('close');
};

/**
 * 点击蒙层关闭
 */
const onMaskTap = (): void => {
  onClose();
};

/**
 * 微信登录
 */
const onWxLogin = async (): Promise<void> => {
  loading.value = true;
  try {
    // 获取微信登录凭证
    const wxCode = await getWxCode();
    
    // 调用登录接口
    const loginResult = await doLogin(wxCode.code);

    // 保存用户信息
    await saveUserInfo(loginResult);

    // 触发登录成功事件
    await emit('success', {
      detail: {
        userInfo: loginResult.userInfo,
        token: loginResult.token
      }
    });

    // 显示成功提示
    uni.showToast({
      title: '登录成功',
      icon: 'success'
    });

    // 关闭弹窗
    onClose();
  } catch (error: any) {
    console.log('CatchClause', error);
    console.error('登录失败：', error);
    uni.showToast({
      title: error.message || '登录失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};



/**
 * 获取微信登录凭证
 */
const getWxCode = (): Promise<WxLoginResponse> => {
  return new Promise((resolve, reject) => {
    uni.login({
      success: (res: any) => {
        if (res.code) {
          resolve({
            code: res.code
          });
        } else {
          reject(new Error('获取登录凭证失败'));
        }
      },
      fail: () => {
        reject(new Error('微信登录失败'));
      }
    });
  });
};

/**
 * 调用后端登录接口
 */
const doLogin = async (code: string): Promise<LoginResult> => {
    // 这里可以调用统一封装的接口
    // 暂时模拟登录接口返回
    try {
        // 调用登录接口
        const res = await loginFun({
            code: code
        });
        if (res.code == 1) {
            const mockResult: LoginResult = {
                userInfo: res.data,
                token: res.data.token,
                userId: res.data.id,
            };
            return mockResult; // 使用 return 而不是 resolve
        } else {
            throw new Error('登录失败');
        }
    } catch (error) {
        console.error('登录错误:', error);
        throw error;
    }
};

/**
 * 保存用户信息
 */
const saveUserInfo = (loginResult: LoginResult): void => {
  try {
    // 保存到本地存储
    uni.setStorageSync('token', loginResult.token);
    uni.setStorageSync('userInfo', loginResult.userInfo);
    uni.setStorageSync('userId', loginResult.userId);

    // 保存到全局数据
    const app = getApp();
    if (app.globalData) {
      app.globalData.token = loginResult.token;
      app.globalData.userInfo = loginResult.userInfo;
      app.globalData.userId = loginResult.userId;
      app.globalData.isLogin = true;
    }
  } catch (error: any) {
    console.log('CatchClause', error);
    console.error('保存用户信息失败：', error);
  }
};

const onAgreementTap = async (num) => {
    console.log(num)
    uni.navigateTo({
        url: '/subpackage/more/more?num=' + num
    })
}

// 暴露给模板使用的变量和方法
defineExpose({
  loading,
  onClose,
  onMaskTap,
  onWxLogin
});
</script>
<style>
.loginContainer {
    padding: 48rpx 32rpx 32rpx 32rpx;
}
.header {
    display: flex;
    flex-direction: column;
    text-align: center;
    margin-bottom: 40rpx;
}
.title {
    font-size: 36rpx;
    font-weight: 600;
    color: #1f1f1f;
}
.desc {
    font-size: 28rpx;
    color: #888;
    margin-top: 12rpx;
}
.content {
    padding: 16rpx 40rpx;
}
.button-row {
    display: flex;
    gap: 24rpx;
    margin-bottom: 40rpx;
}

.login-btn {
    /* flex: 1; */
    width: 156rpx;
    height: 88rpx;
    /* background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); */
    color: white;
    border: none;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: 500;
    /* box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4); */
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
}

.login-btn:hover {
    transform: translateY(-2px);
    /* box-shadow: 0 6px 20px rgba(102, 126, 234, 0.5); */
}

.login-btn:active {
    transform: translateY(0);
    /* box-shadow: 0 2px 10px rgba(102, 126, 234, 0.3); */
}

.cancel-btn {
    /* flex: 1; */
    width: 156rpx;
    height: 88rpx;
    background: #f8f9fa;
    color: #6c757d;
    border: 2rpx solid #dee2e6;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: 500;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
}

.cancel-btn:hover {
    background: #e9ecef;
    border-color: #adb5bd;
    color: #495057;
}

.cancel-btn:active {
    background: #dee2e6;
    transform: scale(0.98);
}
.tips {
    font-size: 28rpx;
    color: #666;
    /* background: #f7f7f7; */
    /* padding: 20rpx 24rpx; */
    border-radius: 16rpx;
    text-align: center;
}
.minor-tips {
    margin-top: 24rpx;
    font-size: 24rpx;
    color: #999;
    text-align: center;
}
/* 协议文字 */
.agreement_text{
    color: #667eea;
    /* text-decoration: underline; */
    font-size: 24rpx;
}
</style>
